/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wii.elpro.web.action;

import com.wii.elpro.dao.jpa.ProdukDAOImpl;
import com.wii.elpro.entity.Produk;
import com.wii.elpro.entity.ProdukMaterial;
import com.wii.elpro.entity.User;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Vyor
 */
public class ProdukSaveMaterialInProdukAction extends org.apache.struts.action.Action {
    //Saving materials ke dalam produk
    //kemudian load lagi datanya

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        try {
            long idProd = Long.parseLong(request.getParameter("idProd"));
            long idMaterial = Long.parseLong(request.getParameter("id"));
            
            ProdukDAOImpl dao = new ProdukDAOImpl();
            Produk p = dao.getProduk(idProd);
            
            if (p.getProdukMaterials() == null) {
                p.setProdukMaterials(new ArrayList<ProdukMaterial>());
            }
            
            ProdukMaterial material = new ProdukMaterial();
            material.setMaterial(dao.getProduk(idMaterial));
            material.setJumlah(Integer.parseInt(request.getParameter("quantity")));
            
            p.getProdukMaterials().add(material);
            
            dao.update(p);
            
            request.setAttribute("prod", dao.getProduk(idProd));
            
            forward = "success";
        } catch (Exception e) {
            forward = "fail";
        }
        return mapping.findForward(forward);
    }
}
